package com.atguigu.eduservice.controller;


import com.atguigu.commonutils.R;
import com.atguigu.eduservice.client.VodClient;
import com.atguigu.eduservice.entity.EduVideo;
import com.atguigu.eduservice.service.EduVideoService;
import com.atguigu.exceptionhandler.GuliException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * 课程视频 前端控制器
 * @author atguigu
 * @since 2021-12-07
 */
@RestController
@RequestMapping("/eduService/video")
@CrossOrigin
public class EduVideoController {

    @Autowired
    private EduVideoService eduVideoService;

    //注入vodClient
    private VodClient vodClient;

    //添加小节
    @PostMapping("addVideo")
    public R addVideo(@RequestBody EduVideo eduVideo) {
        eduVideoService.save(eduVideo);
        return R.ok();
    }

    //删除小节
    // 删除小节同时删除视频
    @DeleteMapping("{id}")
    public R deleteVideo(@PathVariable String id) {
        //根据小节id得到视频id
        EduVideo eduVideo = eduVideoService.getById(id);
        String videoSourceId = eduVideo.getVideoSourceId();

        //判断视频id是否为空
        if (!StringUtils.isEmpty(videoSourceId)) {
            //调用vodCilent删除阿里云视频 运程调用
            R result = vodClient.removeVideo(videoSourceId);
            if (result.getCode() != 20000) {
                throw new GuliException(20001, "删除视频失败,熔断器执行了...");
            }
        }

        //删除小节
        return eduVideoService.removeById(id) ? R.ok() : R.error();
    }

    //修改小节
    @PostMapping
    public R updateVideo(@RequestBody EduVideo eduVideo) {
        eduVideoService.updateById(eduVideo);
        return R.ok();
    }

}

